package com.wf.controller;

import com.wf.domain.User;
import com.wf.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
/**
 * @author mpk
 * @since 2024/8/20 21:08:56
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    // 添加用户
    @PostMapping
    public ResponseEntity<User> addUser(@RequestBody User user) {
        log.info(">>>>>>>>>>");
        User savedUser = userService.saveUser(user);
        return ResponseEntity.ok(savedUser);
    }

    // 更新用户头像
    @PutMapping("/{id}/profile-pic")
    public ResponseEntity<User> updateProfilePic(
            @PathVariable Long id,
            @RequestPart("pic") MultipartFile pic) {
        // TODO 文件上传
        User updatedUser = userService.updateProfilePic(id, pic);
        if (updatedUser != null) {
            return ResponseEntity.ok(updatedUser);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        boolean isDeleted = userService.deleteUser(id);
        if (isDeleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据姓名模糊查询用户信息
    @GetMapping
    public ResponseEntity<List<User>> searchUsersByName(@RequestParam String name) {
        if (!StringUtils.hasText(name)) {
            return ResponseEntity.badRequest().build();
        }
        List<User> users = userService.findUsersByNameContaining(name);
        return ResponseEntity.ok(users);
    }
}
